package com.sunwayworld.basemodule.business.outsource.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sunwayworld.basemodule.business.outsource.bean.LimsOutsourceSampleBean;
import com.sunwayworld.basemodule.business.outsource.service.LimsOutsourceSampleService;
import com.sunwayworld.framework.audit.aunnotation.Audit;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.support.auditable.bean.CoreBpmnParameterDTO;
import com.sunwayworld.framework.utils.CollectionUtils;
import com.sunwayworld.module.sys.bpmn.bean.CoreBpmnInstanceStatusDTO;
import com.sunwayworld.module.sys.bpmn.engine.CoreBpmnRuntimeService;
import com.sunwayworld.module.sys.bpmn.engine.CoreBpmnRuntimeSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.sunwayworld.framework.at.annotation.AuditTrailType;
import com.sunwayworld.framework.at.annotation.AuditTrailEntry;
import com.sunwayworld.framework.spring.annotation.GikamBean;

import com.sunwayworld.basemodule.business.outsource.dao.LimsOutsourceApplyDao;
import com.sunwayworld.basemodule.business.outsource.bean.LimsOutsourceApplyBean;
import com.sunwayworld.basemodule.business.outsource.service.LimsOutsourceApplyService;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Repository
@GikamBean
public class LimsOutsourceApplyServiceImpl implements LimsOutsourceApplyService {

    @Autowired
    private LimsOutsourceApplyDao limsOutsourceApplyDao;

    @Autowired
    @Lazy
    private LimsOutsourceSampleService limsOutsourceSampleService;

    @Override
    @SuppressWarnings("unchecked")
    public LimsOutsourceApplyDao getDao() {
        return limsOutsourceApplyDao;
    }

    @Override
    @Transactional
    @AuditTrailEntry(AuditTrailType.INSERT)
    public Long insert(RestJsonWrapperBean jsonWrapper) {
        LimsOutsourceApplyBean limsOutsourceApply = jsonWrapper.parseUnique(LimsOutsourceApplyBean.class);
        limsOutsourceApply.setId(ApplicationContextHelper.getNextIdentity());

        limsOutsourceApply.setApplyCode(ApplicationContextHelper.getNextSequence(getDao().getTable()));

        getDao().insert(limsOutsourceApply);
        return limsOutsourceApply.getId();
    }

    @Transactional
    @AuditTrailEntry(AuditTrailType.PROCESS_COMPLETE)
    @Audit("AUDIT.PROCESS_COMPLETE")
    public List<CoreBpmnInstanceStatusDTO<Long>> completeTask(RestJsonWrapperBean wrapper) {
        List<LimsOutsourceApplyBean> itemList = wrapper.parse(this.getDao().getType());
        if (itemList.isEmpty()) {
            return CollectionUtils.emptyList();
        } else {
            this.checkAndUpdateVersion(itemList);
            CoreBpmnRuntimeService runtimeService = ApplicationContextHelper.getBean(CoreBpmnRuntimeService.class);
            List<Long> itemIdList = itemList.stream().map(LimsOutsourceApplyBean::getId).collect(Collectors.toList());

            // 审核通过刷新状态，可以在结果录入显示
            LimsOutsourceApplyBean update = new LimsOutsourceApplyBean();
            update.setStatus("logged");
            getDao().updateByIds(update, itemIdList, "status");

            List<LimsOutsourceApplyBean> selectItemList = this.getBpmnVarsItemList(itemIdList);
            List<CoreBpmnRuntimeSource<LimsOutsourceApplyBean, Long>> runtimeSourceList = this.parseAuditableRuntimeSource(itemIdList, CoreBpmnParameterDTO.of(wrapper), this.getBpmnVars(wrapper, selectItemList));
            List<CoreBpmnInstanceStatusDTO<Long>> instanceStatusList = runtimeService.completeTask(runtimeSourceList);
            this.autoPass(runtimeSourceList, instanceStatusList);
            return instanceStatusList;
        }
    }

    @Override
    public JSONObject insertMulti(RestJsonWrapperBean wrapperBean) {
        JSONObject req = new JSONObject();
        List<LimsOutsourceApplyBean> items = wrapperBean.parse(LimsOutsourceApplyBean.class);
        if (items.isEmpty()) {
            return req;
        }
        List<Long> ids = ApplicationContextHelper.getNextIdentityList(items.size());
        List<String> applyCodes = ApplicationContextHelper.getNextSequenceList(getDao().getTable(), items.size());
        for (int i = 0; i < items.size(); i++) {
            LimsOutsourceApplyBean oa = items.get(i);
            oa.setId(ids.get(i));
            oa.setApplyCode(applyCodes.get(i));
        }
        getDao().insert(items);
        return req;
    }

    @Override
    public JSONObject resultDone(RestJsonWrapperBean wrapperBean) {
        JSONObject req = new JSONObject();
        List<LimsOutsourceApplyBean> items = wrapperBean.parse(LimsOutsourceApplyBean.class);
        if (items.isEmpty()) {
            return req;
        }
        List<Long> ids = items.stream().map(LimsOutsourceApplyBean::getId).collect(Collectors.toList());
        LimsOutsourceApplyBean update = new LimsOutsourceApplyBean();
        update.setStatus("done");
        getDao().updateByIds(update, ids, "status");
        return req;
    }

    @Override
    public JSONObject setCourier(RestJsonWrapperBean wrapperBean) {
        JSONObject req = new JSONObject();
        String courierNumber = wrapperBean.getParamValue("courierNumber");
        String courier = wrapperBean.getParamValue("courier");
        List<LimsOutsourceApplyBean> items = wrapperBean.parse(LimsOutsourceApplyBean.class);
        if (items.isEmpty()) {
            return req;
        }
        List<Long> ids = items.stream().map(LimsOutsourceApplyBean::getId).collect(Collectors.toList());
        LimsOutsourceApplyBean update = new LimsOutsourceApplyBean();
        update.setCourier(courier);
        update.setCourierNumber(courierNumber);
        getDao().updateByIds(update, ids, "courierNumber", "courier");
        return req;
    }

    @Override
    public JSONObject submitCheck(RestJsonWrapperBean wrapperBean) {
        JSONObject req = new JSONObject();
        req.put("flag", "1");
        List<LimsOutsourceApplyBean> applyBeans = wrapperBean.parse(LimsOutsourceApplyBean.class);
        if (applyBeans.isEmpty()) {
            return req;
        }
        List<Long> ids = applyBeans.stream().map(LimsOutsourceApplyBean::getId).collect(Collectors.toList());
        applyBeans = this.selectListByIds(ids);
        List<LimsOutsourceSampleBean> sampleBeans = limsOutsourceSampleService.selectListByFilter(SearchFilter.instance().match("applyId", ids).filter(MatchPattern.OR));
        StringBuffer message = new StringBuffer();
        applyBeans.forEach(ap -> {
            Optional<LimsOutsourceSampleBean> optional = sampleBeans.stream().filter(s -> s.getApplyId().equals(ap.getId())).findAny();
            if (!optional.isPresent()) {
                message.append(ap.getApplyCode()).append(",<br/>");
                req.put("flag", "0");
            }
        });
        if (message.length() > 0) {
            req.put("message", message.append("外包单请添加样本信息！"));
        }
        return req;
    }
}
